package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IVoucherOrderService voucherOrderService;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private static final ExecutorService SECKILL_ORDER_EXECURTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init() {
        SECKILL_ORDER_EXECURTOR.submit(() -> {
            while (true) {
                try {
                    // 1. 获取消息队列中的消息 xreadgroup group g1 c1 count 1 block 2000 stream streams.order >
                    String quickName = "stream.order";
                    List<MapRecord<String, Object, Object>> mapRecordList = stringRedisTemplate.opsForStream().read(
                            // org.springframework.data.redis.connection.stream
                            // 设置消费者组和消费者
                            Consumer.from("g1", "c1"),
                            // 每次消费1个,阻塞两秒钟
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            // 读取最新的未消费的
                            StreamOffset.create(quickName, ReadOffset.lastConsumed())
                    );

                    // 2. 判断消息是否获取成功
                    if (mapRecordList == null || mapRecordList.isEmpty()) {
                        continue;
                    }
                    // 3. 解析消息
                    MapRecord<String, Object, Object> entries = mapRecordList.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 4. 如果获取成功，可以下单
                    voucherOrderService.getResult(voucherOrder);
                    // 5. ACK 确认
                    stringRedisTemplate.opsForStream().acknowledge(quickName, "g1", entries.getId());
                } catch (Exception e) {
                    // 出现异常，就去 pendingList中查询
                    log.error("处理订单异常");
                    handlePendingList();
                }
            }
        });
    }

    private void handlePendingList() {
        while (true) {
            try {
                // 1. 获取消息队列中的消息 pending-list group g1 c1 count 1 block 2000 stream streams.order >
                String quickName = "stream.order";
                List<MapRecord<String, Object, Object>> mapRecordList = stringRedisTemplate.opsForStream().read(
                        // org.springframework.data.redis.connection.stream
                        // 设置消费者组和消费者
                        Consumer.from("g1", "c1"),
                        // 每次消费1个,阻塞两秒钟
                        StreamReadOptions.empty().count(1),
                        // 读取最新的未消费的
                        StreamOffset.create(quickName, ReadOffset.from("0"))
                );

                // 2. 判断消息是否获取成功，说明pending 中没有消息
                if (mapRecordList == null || mapRecordList.isEmpty()) {
                    break;
                }
                // 3. 解析消息
                MapRecord<String, Object, Object> entries = mapRecordList.get(0);
                Map<Object, Object> value = entries.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                // 4. 如果获取成功，可以下单
                voucherOrderService.getResult(voucherOrder);
                // 5. ACK 确认
                stringRedisTemplate.opsForStream().acknowledge(quickName, "g1", entries.getId());
            } catch (Exception e) {
                // 出现异常，就去 pendingList中查询
                log.error("处理pend-list订单异常");
                break;
            }
        }
    }


    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        // 生成下单列表ID
        long orderId = redisIdWorker.nextId("order");
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),
                String.valueOf(orderId));
        assert result != null;
        if (result != 0) {
            return Result.fail(result == 1 ? "库存不足" : "不能重复下单");
        }
        return Result.ok(orderId);
    }

    @Transactional
    public void getResult(VoucherOrder voucherOrder) {
        RLock lock = redissonClient.getLock("lock:order:" + voucherOrder.getUserId());
        boolean tryLock = lock.tryLock();
        if (!tryLock) {
            log.error("当前用户已经领取过了...");
            return;
        }
        Long count = lambdaQuery().eq(VoucherOrder::getUserId, voucherOrder.getUserId())
                .eq(VoucherOrder::getVoucherId, voucherOrder.getVoucherId())
                .count();
        if (count > 0) {
            log.error("当前用户已经领取过了...");
            return;
        }

        // 可以继续抢，扣减库存
        boolean flag = seckillVoucherService.lambdaUpdate().setSql("stock = stock - 1")
                .eq(SeckillVoucher::getVoucherId, voucherOrder.getVoucherId())
                .gt(SeckillVoucher::getStock, 0)
                .update();

        if (!flag)
            log.error("券抢完啦！");
        // 新增订单
        save(voucherOrder);
    }
}
